package com.pri.chat.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.LoginBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.netease.nim.uikit.support.permission.MPermission;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionDenied;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionGranted;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionNeverAskAgain;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.pri.chat.MainActivity;
import com.pri.chat.R;
import com.pri.chat.base.BaseActivity;
import com.pri.chat.base.SplashActivity;
import com.pri.chat.base.TcWebActivity;
import com.pri.chat.bean.WeChatBean;
import com.pri.chat.model.RegModel;
import com.pri.chat.nim.DemoCache;
import com.pri.chat.nim.Preferences;
import com.pri.chat.nim.UserPreferences;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.StringUtils;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogSex;
import com.vondear.rxui.view.dialog.RxDialogTool;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.MediaType;
import okhttp3.RequestBody;


/**
 * Created by JY on 2017/11/15.
 */

public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";
    /**
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };
    private final int BASIC_PERMISSION_REQUEST_CODE = 110;
    @BindView(R.id.et_login_name)
    EditText etLoginName;
    @BindView(R.id.iv_clean_phone)
    ImageView ivCleanPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_xieyi)
    TextView tvXieyi;
    @BindView(R.id.tv_ys)
    TextView tvYs;
    @BindView(R.id.btn_login)
    TextView btnLogin;
    @BindView(R.id.tv_reg)
    TextView tvReg;
    @BindView(R.id.wxLogin)
    View wxLogin;


    private AbortableFuture<LoginInfo> loginRequest;

    /**
     * ***************************************** 登录 **************************************
     */

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login_layout;
    }

    @Override
    public void initView() {
        etLoginName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s) && ivCleanPhone.getVisibility() == View.GONE) {
                    ivCleanPhone.setVisibility(View.VISIBLE);
                } else if (TextUtils.isEmpty(s)) {
                    ivCleanPhone.setVisibility(View.GONE);
                }
            }
        });
        requestBasicPermission();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//            ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION,
//                    ACCESS_BACKGROUND_LOCATION
//            ),101)
//        } else {
//            ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),101)
//        }
    }

    @Override
    public void initData() {
    }


    private void requestBasicPermission() {
        MPermission.with(LoginActivity.this).setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS).request();
    }

    @OnClick({R.id.wxLogin, R.id.btn_login, R.id.tv_xieyi, R.id.tv_ys, R.id.iv_clean_phone, R.id.tv_reg, R.id.tv_forget_pwd})
    public void onViewClicked(View view) {
        String mobile = etLoginName.getText().toString();
        String code = etCode.getText().toString();
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.tv_xieyi:
                intent.setClass(this, TcWebActivity.class);
                intent.putExtra("title", "用户协议");
                intent.putExtra("url", HttpMethods.BASE_URL + "p/front_editorHtmlShow.html?code=yonghuxieyiCode");
                startActivity(intent);
                break;
            case R.id.tv_ys:
                intent.setClass(this, TcWebActivity.class);
                intent.putExtra("title", "隐私协议");
                intent.putExtra("url", HttpMethods.BASE_URL + "p/front_editorHtmlShow.html?code=yinsixieyiCode");
                startActivity(intent);
                break;
            case R.id.btn_login:
                if (mobile.isEmpty()) {
                    RxToast.normal(getString(R.string.login_mobile_empty));
                } else if (code.isEmpty()) {
                    RxToast.normal(getString(R.string.login_pwd_empty));
                } else {
                    login(mobile, code);
                }

                break;
            case R.id.tv_reg:
                RxActivityTool.skipActivityForResult(activity, RegActivity.class, 1);
//                RxActivityTool.skipActivity(this, RegisterByPhoneActivity.class);
                break;
            case R.id.tv_forget_pwd:
                RxActivityTool.skipActivity(this, ForgetPwdActivity.class);
                break;
            case R.id.iv_clean_phone:
                etLoginName.setText("");
                etLoginName.setHint("请输入您的手机号");
                break;
            case R.id.wxLogin:
                weChatLogin();
                break;

        }
    }

    private void login(final String mobile, final String pwd) {
        SubscriberOnNextListener<BaseBean<LoginBean>> onNextListener = baseBean -> {
            if (baseBean.isSuccess()) {
                nimLogin(baseBean.getData());
//                SharedHelper.saveMobile(LoginActivity.this, baseBean.getData().getMobile());
//                SharedHelper.saveSex(mContext, baseBean.getData().getSex());
//                SharedHelper.saveHeadPic(mContext, baseBean.getData().getHeadPic());
//                SharedHelper.saveNick(mContext,baseBean.getData().getNcName());
//                SharedHelper.saveSex(mContext, baseBean.getData().getSex());
//                SharedHelper.saveId(LoginActivity.this, baseBean.getData().getId());
//                SharedHelper.saveNimToken(LoginActivity.this, baseBean.getData().getWyToken());
//                SharedHelper.saveNimId(LoginActivity.this, baseBean.getData().getUserCode());
//                SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
//                sp.edit().putBoolean("isFirst", false).apply();
//                Bundle bundle = new Bundle();
//                bundle.putString("type", baseBean.getData().getFirstLogin());
//                bundle.putString("money", baseBean.getData().getTxMoney());
//                RxActivityTool.skipActivity(LoginActivity.this, MainActivity.class, bundle);
//                finish();
            } else {
                dismissProgressDialog();
                RxToast.normal(baseBean.getMsg());
            }
        };
        RegModel regModel = new RegModel();//登录上传参数
        regModel.setMobile(mobile);
        regModel.setPassword(pwd);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(regModel));
        HttpMethods.getInstance().login(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    /**
     * 网易登录
     *
     * @param data
     */
    private void nimLogin(LoginBean data) {
        final String account = data.getId();
        final String token = data.getWyToken();
        // 登录
        loginRequest = NimUIKit.login(new LoginInfo(account, token),
                new RequestCallback<LoginInfo>() {

                    @Override
                    public void onSuccess(LoginInfo param) {
                        RxDialogTool.loadingHttpCancel();
                        LogUtil.i(TAG, "login success");
                        onLoginDone();
                        DemoCache.setAccount(account);
                        saveLoginInfo(account, token);
                        // 初始化消息提醒配置
                        initNotificationConfig();
                        // 进入主界面
                        SharedHelper.saveMobile(LoginActivity.this, data.getMobile());
                        SharedHelper.saveSex(mContext, data.getSex());
                        SharedHelper.saveHeadPic(mContext, data.getHeadPic());
                        SharedHelper.saveNick(mContext, data.getNcName());
                        SharedHelper.saveSex(mContext, data.getSex());

//                        SharedHelper.saveKeyValueForString(mContext,"fbyw",data.getTcyw());
                        SharedHelper.saveKeyValueForString(mContext, "SVIPCODE", data.getSuperVipCode());
                        SharedHelper.saveKeyValueForString(mContext, "SVIP", data.getSuperVip());
                        SharedHelper.saveKeyValueForString(mContext, "hongbao", data.getTxMoney());
                        SharedHelper.saveKeyValueForString(mContext, "show", data.getShowHongBao());
                        SharedHelper.saveKeyValueForString(mContext, "trueName", data.getTrueName());
                        SharedHelper.saveKeyValueForString(mContext, "zfbNo", data.getZfbNo());
                        SharedHelper.saveKeyValueForString(mContext, "wxNo", data.getWxNo());
                        SharedHelper.saveKeyValueForString(mContext, "sjId", data.getInviteMemberId());
                        SharedHelper.saveId(LoginActivity.this, data.getId());
                        SharedHelper.saveNimToken(LoginActivity.this, data.getWyToken());
                        SharedHelper.saveNimId(LoginActivity.this, data.getUserCode());
                        SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
                        sp.edit().putBoolean("isFirst", false).apply();

//                        RxActivityTool.skipActivity(LoginActivity.this, DaoHangActivity.class);
                        if ("1".equals(data.getTcyw())) {
                            RxActivityTool.skipActivity(LoginActivity.this, DaoHangActivity.class);
                        } else {
                            RxActivityTool.skipActivity(LoginActivity.this, MainActivity.class);
                        }
                    }

                    @Override
                    public void onFailed(int code) {
                        RxDialogTool.loadingHttpCancel();
                        RxToast.normal(getString(R.string.login_fail));
                    }

                    @Override
                    public void onException(Throwable exception) {
                        RxDialogTool.loadingHttpCancel();
                        RxToast.normal(getString(R.string.login_error));
                    }
                });
    }

    /**
     * 释放loginRequest
     */
    private void onLoginDone() {
        loginRequest = null;
    }

    /**
     * 保存登录信息
     *
     * @param account
     * @param token
     */
    private void saveLoginInfo(final String account, final String token) {
        Preferences.saveUserAccount(account);
        Preferences.saveUserToken(token);
    }

    /**
     * 初始化消息
     */
    private void initNotificationConfig() {
        // 初始化消息提醒
        NIMClient.toggleNotification(UserPreferences.getNotificationToggle());
        // 加载状态栏配置
        StatusBarNotificationConfig statusBarNotificationConfig = UserPreferences.getStatusConfig();
        if (statusBarNotificationConfig == null) {
            statusBarNotificationConfig = DemoCache.getNotificationConfig();
            UserPreferences.setStatusConfig(statusBarNotificationConfig);
        }
        // 更新配置
        NIMClient.updateStatusBarNotificationConfig(statusBarNotificationConfig);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
//        ToastHelper.showToast(this, "权限获取成功！");
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
//        ToastHelper.showToast(this, "权限获取失败！");
    }

    private WeChatBean wcBean;

    private void weChatLogin() {
        Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
        //判定客户端是否可用
        if (wechat.isClientValid()) {
            //客户端可用
        }
        if (wechat.isAuthValid()) {
            wechat.removeAccount(true);
        }
        wechat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, final HashMap<String, Object> hashMap) {
                /*platform.getDb().exportData()获取用户公共信息*/
                Log.d("ShareSDK", "onComplete ---->  登录成功" + platform.getDb().exportData());
                platform.getDb().getUserId();
                wcBean = new Gson().fromJson(platform.getDb().exportData(), WeChatBean.class);
                handler.sendEmptyMessage(10);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.d("ShareSDK", "onError ---->  登录失败" + throwable.toString());
                Log.d("ShareSDK", "onError ---->  登录失败" + throwable.getStackTrace().toString());
                Log.d("ShareSDK", "onError ---->  登录失败" + throwable.getMessage());
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.d("ShareSDK", "onCancel ---->  登录取消");
            }
        });
        wechat.SSOSetting(false);
        wechat.showUser(null);
    }

    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 10) {
                authorLogin();
            }else if(msg.what == 100){
                if(!StringUtils.isEmpty(yqmCode)){
                    SharedHelper.saveKeyValueForString(mContext,"yqmCode",yqmCode);
                }
            }
        }
    };


    private String sex = "";
    private RxDialogSex rxDialogSex;

    private void initSexDialog() {
        rxDialogSex = new RxDialogSex(this);
        rxDialogSex.setManListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sex = "男";
                rxDialogSex.getManImage().setBackgroundResource(R.drawable.btn_sex_select_shape);
                rxDialogSex.getWoManImage().setBackgroundColor(getResources().getColor(R.color.white));
            }
        });
        rxDialogSex.setWoManListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sex = "女";
                rxDialogSex.getManImage().setBackgroundColor(getResources().getColor(R.color.white));
                rxDialogSex.getWoManImage().setBackgroundResource(R.drawable.btn_sex_select_shape);
            }
        });
        rxDialogSex.setSureListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (StringUtils.isEmpty(sex)) {
                    RxToast.normal("请选择性别！");
                    return;
                }
                String inviteCode = rxDialogSex.getInviteEdit().getText().toString();
                registerMember(inviteCode);
            }
        });

        sex = "";
        rxDialogSex.getManImage().setBackgroundColor(getResources().getColor(R.color.white));
        rxDialogSex.getWoManImage().setBackgroundColor(getResources().getColor(R.color.white));

        rxDialogSex.show();
    }

    private void registerMember(String inviteCode) {
        String deviceId = RxDeviceTool.getIMEI(this);
        if (StringUtils.isEmpty(deviceId)) {
            RxToast.normal("没有获取到设备ID，无法注册！");
            return;
        }
        SubscriberOnNextListener<BaseBean<LoginBean>> onNextListener = baseBean -> {
            if (baseBean.isSuccess()) {
                rxDialogSex.dismiss();
                nimLogin(baseBean.getData());
            } else {
                RxToast.normal(baseBean.getMsg());
            }
        };
        RegModel regModel = new RegModel();//注册上传参数
        regModel.setSex(sex);
        regModel.setOpenid(wcBean.getOpenid());
        regModel.setHeadPic(wcBean.getIcon());
        regModel.setNcName(wcBean.getNickname());
        regModel.setInvitedUserCode(inviteCode);
        regModel.setDeviceId(deviceId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(regModel));
        HttpMethods.getInstance().registerWeChat(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }


    private void authorLogin() {
        SubscriberOnNextListener<BaseBean<LoginBean>> onNextListener = baseBean -> {
            if (baseBean.isSuccess()) {
                nimLogin(baseBean.getData());
            } else {
                RxDialogTool.loadingHttpCancel();
//                RxToast.normal("微信登录稍后开通~");
                //注册
                Bundle bundle = new Bundle();
                bundle.putString("openId", wcBean.getOpenid());
                bundle.putString("headPic", wcBean.getIcon());
                bundle.putString("ncName", wcBean.getNickname());
                bundle.putString("sex", wcBean.getGender());
                RxActivityTool.skipActivityForResult(activity, RegActivity.class, bundle, 0);
            }
        };
        Map<String, Object> params = new HashMap<String, Object>();//登录上传参数
        params.put("openid", wcBean.getOpenid());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().authorLogin(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    private Handler handlerYzm = new Handler();

    private String yqmCode;

    @Override
    protected void onResume() {
        super.onResume();

        handlerYzm.postDelayed(new Runnable() {
            @Override
            public void run() {
                yqmCode = StringUtils.getClipboardContentTest(mContext);
//                etLoginName.setText(yqmCode);
                if(!StringUtils.isEmpty(yqmCode) && yqmCode.startsWith("YH_")){
                    SharedHelper.saveKeyValueForString(mContext,"yqmCode",yqmCode.split("_")[1]);
                }
            }
        }, 500);
        if (isAdopt()) {
            finish();
        }

    }

    private boolean isAdopt() {
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatusIntent = registerReceiver(null, intentFilter);
        int voltage = batteryStatusIntent.getIntExtra("voltage", 99999);
        int temperature = batteryStatusIntent.getIntExtra("temperature", 99999);
        if (((voltage == 0) && (temperature == 0)) || ((voltage == 10000) && (temperature == 0))) {
            //这是通过电池的伏数和温度来判断是真机还是模拟器
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0) {
                authorLogin();
            } else if (requestCode == 1) {
                String mobile = data.getStringExtra("mobile");
                String password = data.getStringExtra("password");
                etLoginName.setText(mobile);
                etCode.setText(password);
                login(mobile, password);
            }
        }
    }
}
